package com.morningstar.gateway.filter;

import com.morningstar.common.constants.HeaderConstants;
import com.morningstar.gateway.constants.FilterOrderedConstant;
import com.morningstar.gateway.entity.LogEntity;
import com.morningstar.gateway.utils.IpUtils;
import com.morningstar.gateway.utils.LoggerUtils;
import io.netty.buffer.UnpooledByteBufAllocator;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author yls
 */
@Component
public class ResponseLoggerFilter implements GlobalFilter, Ordered {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

//    @Autowired
//    Tracer tracer;
//
//    @Autowired
//    CurrentTraceContext currentTraceContext;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            ServerHttpRequest request = exchange.getRequest();
            ServerRequest serverRequest = ServerRequest.create(exchange, HandlerStrategies.withDefaults().messageReaders());
            URI requestUri = request.getURI();
            String uriQuery = requestUri.getQuery();
            HttpHeaders headers = request.getHeaders();
            MediaType mediaType = headers.getContentType();
            String schema = requestUri.getScheme();
            String method = request.getMethod().toString();

            // 只记录http、https请求
            if ((!"http".equals(schema) && !"https".equals(schema))) {
                return chain.filter(exchange);
            }
            final AtomicReference<String> requestBody = new AtomicReference<>();// 原始请求体
            // 排除流文件类型,比如上传的文件contentType.contains("multipart/form-data")
            if (Objects.nonNull(mediaType) && LoggerUtils.isUploadFile(mediaType)) {
                requestBody.set("上传文件");
                return chain.filter(exchange);
            } else {
                if (method.equals("GET")) {
                    if (StringUtils.isNotBlank(uriQuery)) {
                        requestBody.set(uriQuery);
                    }
                } else if (headers.getContentLength() > 0){
                    return serverRequest.bodyToMono(String.class).flatMap(reqBody -> {
                        requestBody.set(reqBody);
                        // 重写原始请求
                        ServerHttpRequestDecorator requestDecorator = new ServerHttpRequestDecorator(exchange.getRequest()) {
                            @Override
                            public HttpHeaders getHeaders() {
                                HttpHeaders httpHeaders = new HttpHeaders();
                                httpHeaders.putAll(super.getHeaders());
                                return httpHeaders;
                            }
                            @Override
                            public Flux<DataBuffer> getBody() {
                                NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(new UnpooledByteBufAllocator(false));
                                DataBuffer bodyDataBuffer = nettyDataBufferFactory.wrap(reqBody.getBytes());
                                return Flux.just(bodyDataBuffer);
                            }
                        };
                        ServerHttpResponseDecorator responseDecorator = getServerHttpResponseDecorator(exchange,
                                requestBody);
                        return chain.filter(exchange.mutate()
                                .request(requestDecorator)
                                .response(responseDecorator)
                                .build());
                    });
                }
                ServerHttpResponseDecorator decoratedResponse = getServerHttpResponseDecorator(exchange,
                        requestBody);
                return chain.filter(exchange.mutate()
                        .response(decoratedResponse)
                        .build());
            }

        } catch (Exception e) {
            logger.error(ExceptionUtils.getStackTrace(e));
//            WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext, exchange, () -> logger.error(ExceptionUtils.getStackTrace(e)));
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return FilterOrderedConstant.RESPONSE_FILTER_ORDER;
    }

    /**
     *
     * @param exchange
     * @param requestBody
     * @return
     */
    private ServerHttpResponseDecorator getServerHttpResponseDecorator(ServerWebExchange exchange,
                                                                       AtomicReference<String> requestBody) {
        // 获取response的返回数据
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        HttpStatusCode httpStatusCode = originalResponse.getStatusCode();
        ServerHttpRequest request = exchange.getRequest();
        URI requestUri = request.getURI();
        String path = requestUri.getPath();

        // 封装返回体
        return new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        DataBuffer join = bufferFactory.join(dataBuffers);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        DataBufferUtils.release(join);

                        String responseBody;
                        MediaType contentType = originalResponse.getHeaders().getContentType();

                        // 下载文件时 不需要打印具体响应内容 标识即可
                        if (Objects.nonNull(contentType) && LoggerUtils.isUploadFile(contentType)) {
                            responseBody = "下载文件";
                        } else {
                            Charset charset = LoggerUtils.getMediaTypeCharset(contentType);
                            responseBody = new String(content, charset);
                            // 打印日志
                            AtomicReference<String> newResponseBody = new AtomicReference<>(responseBody);
                            // 报文结构转换
                            responseBody = newResponseBody.get();
                        }

                        LogEntity logEntity = buildLog(responseBody, requestBody.get(), httpStatusCode, request);
                        exchange.getSession().subscribe(webSession -> {
                            logEntity.setSessionId(webSession.getId());
                        });
                        logger.info(LoggerUtils.toJsonString(logEntity));
//                        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext,
//                                exchange, () -> logger.info("requestId {}", logEntity.getRequestId()));
//                        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext,
//                                exchange, () -> logger.info("hostName {}", logEntity.getHostName()));
//                        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext,
//                                exchange, () -> logger.info("ip {}", logEntity.getIp()));
//                        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext,
//                                exchange, () -> logger.info("requestMethod {}", logEntity.getRequestMethod()));
//                        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext,
//                                exchange, () -> logger.info("requestUrl {}", logEntity.getRequestUrl()));
//                        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext,
//                                exchange, () -> logger.info("status {}", logEntity.getStatus()));
//                        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext,
//                                exchange, () -> logger.info("requestBody {}", logEntity.getRequestBody()));
//                        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext,
//                                exchange, () -> logger.info("responseBody {}", logEntity.getResponseBody()));
//                        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext,
//                                exchange, () -> logger.info("sessionId {}", logEntity.getSessionId()));
//                        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext,
//                                exchange, () -> logger.info("serverIp {}", logEntity.getServerIp()));
                        return bufferFactory.wrap(content);
                    }));
                }
                return super.writeWith(body);
            }
        };
    }

    /**
     * @param responseBody
     * @param requestBody
     * @param httpStatus
     * @param request
     * @return
     */
    private LogEntity buildLog(String responseBody, String requestBody, HttpStatusCode httpStatus, ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String requestId = headers.getFirst(HeaderConstants.REQUEST_ID);
        String method = request.getMethod().toString();
        URI requestUri = request.getURI();
        String uriQuery = requestUri.getQuery();
        String path = requestUri.getPath();
        String url = path + (StringUtils.isNotBlank(uriQuery) ? "?" + uriQuery : "");

        LogEntity logEntity = new LogEntity();
        logEntity.setRequestUrl(url);
        logEntity.setRequestBody(requestBody);
        logEntity.setResponseBody(responseBody);
        logEntity.setRequestMethod(method);
        if (Objects.nonNull(httpStatus)) {
            logEntity.setStatus(httpStatus.value());
        }
        logEntity.setRequestId(requestId);
        logEntity.setIp(IpUtils.getClientIp(request));
        return logEntity;
    }
}
